package com.atguigu.exam.service.impl;

import com.atguigu.exam.properties.MinioProperties;
import com.atguigu.exam.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * projectName: com.atguigu.exam.service.impl
 *
 * @author: 赵伟风
 * description:
 */
@Service
@Slf4j
@EnableConfigurationProperties(value = MinioProperties.class)
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;


    @Override
    public String uploadFile(MultipartFile file) {
        try {
            //1.创建客户端对象
            MinioClient.builder().
                    endpoint(minioProperties.getEndpoint())
                    .credentials(minioProperties.getAccessKey(),minioProperties.getSecretKey())
                    .build();
            //检查桶是否存在
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (isExist){
                System.out.println("Bucket "+minioProperties.getBucketName()+" already exists");
            } else{
                //如果桶不存在则创建它
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            }

            //获取文件名
            String originalFilename = file.getOriginalFilename();
            //获取上传文件的后缀
            String suffix = originalFilename.substring(originalFilename.indexOf("."));
            //是由UUID随即生成一个字符串作为文件名
            String preffix = UUID.randomUUID().toString().replace("-", "");
            //对当前日期格式化
            String format = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
            //创建新的文件名
            String fileName = format+"/"+preffix+suffix;
            //获取输入流
            InputStream is = file.getInputStream();
            //获取文件大小
            long size = file.getSize();

            //2.创建PutObject对象
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    //minio服务器中桶的名字
                    .bucket(minioProperties.getBucketName())
                    //设置上传到minio服务器中文件名
                    .object(fileName)
                    //设置输入流
                    .stream(is, size, -1)
                    .build();
            //使用putObject上传文件到Minio服务器的桶中
            minioClient.putObject(putObjectArgs);
            return minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+fileName;
        } catch (Exception e) {
            System.out.println("Error occurred: "+e);
        }
        return null;
    }
}
